<template>
  <div>
    <!--头部行表单 ：增加 -->
    <div class="filter-container">
      <el-button type="primary" icon="el-icon-document-add" @click="handleAdd">新增</el-button>
    </div>

    <!-- 数据列表 编辑 删除 -->
    <div class="list-container">
      <el-table :data="dataList" fit highlight-current-row style="width: 100%;">
        <el-table-column prop="sort" label="序号" width="55" align="center"></el-table-column>

        <el-table-column label="轮播图片" width="200" align="center">
          <template slot-scope="scope">
            <el-image :src="$fullUrl(scope.row.img)"
                      :preview-src-list="[$fullUrl(scope.row.img)]"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="goodsId" label="商品id"></el-table-column>

        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row.id)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 数据量不多，这里就不进行分页处理了 -->
    </div>

    <!-- 编辑弹出框 -->
    <home-carousel-edit v-if="editDialogVisible" ref="editDialog" @refreshDataList="loadDataList"/>
  </div>
</template>

<script>
import HomeCarouselEdit from './components/HomeCarouselEdit.vue';
import * as HomeAPI from '@/api/home.js';

export default {
  name: 'homeCarouselList',
  components: {
    HomeCarouselEdit
  },
  data() {
    return {
      dataList: [], //列表数据
      editDialogVisible: false //编辑对话框
    };
  },

  created() {
    this.loadDataList(); // 初始列表数据
  },

  methods: {
    // 获取列表数据
    loadDataList() {
      HomeAPI.getCarouselList().then(result => {
        this.dataList = result.data;
      });
    },

    // 删除操作
    handleDelete(id) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 选择了确认，则删除后端数据库中的记录
          HomeAPI.deleteById(id)
            .then(() => {
              this.loadDataList(); //刷新页面列表数据
              this.$message.success('删除成功');
            })
            .catch(() => {
            });
        })
        .catch(() => {
        });
    },

    // 编辑操作
    handleUpdate(id) {
      this.editDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.editDialog.init(id);
      });
    },

    // 增加按钮
    handleAdd() {
      this.editDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.editDialog.init(); //新增时id为null
      });
    },
  }
};
</script>

<style scoped></style>
